<?php

/**
 * This is the model class for table "{{products}}".
 *
 * The followings are the available columns in table '{{products}}':
 * @property integer $id
 * @property string $p_id
 * @property integer $p_type_id
 * @property string $p_name
 * @property string $p_comment
 * @property string $info_detail
 * @property string $p_specs
 * @property double $unit_price
 * @property string $images
 * @property string $create_datetime
 * @property string $update_datetime
 * @property integer $show
 * @property integer $del_flg
 *
 * The followings are the available model relations:
 * @property ProductsType $pType
 */
class Products extends CActiveRecord
{
	public $imageUpload;
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{products}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('p_id, p_type_id, p_name, unit_price, create_datetime', 'required'),
			array('p_type_id, show, del_flg', 'numerical', 'integerOnly'=>true),
			array('unit_price', 'numerical'),
			array('p_id', 'length', 'max'=>45),
			array('p_name', 'length', 'max'=>100),
			array('p_comment', 'length', 'max'=>200),
			array('imageUpload', 'file', 'types' => 'jpg, gif, png', 'allowEmpty' => true,'message'=>'Invalid','on'=>'create'),
			array('images', 'file', 'types' => 'jpg, gif, png','message'=>'Hình ảnh không được phép rỗng','on'=>'create'),
			array('info_detail, p_specs, update_datetime', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, p_id, p_type_id, p_name, p_comment, info_detail, p_specs, unit_price, create_datetime, update_datetime, show, del_flg', 'safe', 'on'=>'search'),
		);
	}
	protected function beforeSave()	{
		$this->imageUpload = CUploadedFile::getInstance($this, 'images');
		//print_r($this->imageUpload);die;
		if (isset($this->imageUpload)) {
			$current_name = $this->imageUpload->name;
			$fileName     	= $_POST['Products']['p_name'];//$this->imageUpload->name; //preg_replace('/[^\w\._]+/', '_', $_POST['Products']['p_name']);
			$new_filename   = pathinfo($fileName, PATHINFO_FILENAME);
			$fileName_replace = THclass::convert_name_vi($new_filename);
			$ext        	= pathinfo($current_name, PATHINFO_EXTENSION);
			$newName        = hash("adler32",Date("His")).'-'.$fileName_replace.'.'.$ext;
			//print_r($newName);die;
			$uploadFolder = Yii::getPathOfAlias('webroot') . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . date('Y-m-d');
			if (!is_dir($uploadFolder)) {
				mkdir($uploadFolder, 0755, TRUE);
			}
			$uploadFile = $uploadFolder . DIRECTORY_SEPARATOR . $newName;
			$this->imageUpload->saveAs($uploadFile); //Upload file thong qua object CUploadedFile
			$this->images = '/upload/' . date('Y-m-d') . '/' . $newName; //Lưu path vào csdl
		}
		return parent::beforeSave();
	}
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'pType' => array(self::BELONGS_TO, 'ProductsType', 'p_type_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'p_id' => 'Mã sản phẩm',
			'p_type_id' => 'Loại sản phẩm',
			'p_name' => 'Tên sản phẩm',
			'p_comment' => 'Ghi chú',
			'info_detail' => 'Thông tin chi tiết',
			'p_specs' => 'Thông số kỹ thuật',
			'unit_price' => 'Đơn giá',
			'images' => 'Hình ảnh',
			'create_datetime' => 'Ngày tạo',
			'update_datetime' => 'Ngày cập nhật',
			'show' => 'Ẩn hiện',
			'del_flg' => 'Xóa',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('p_id',$this->p_id,true);
		$criteria->compare('p_type_id',$this->p_type_id);
		$criteria->compare('p_name',$this->p_name,true);
		$criteria->compare('p_comment',$this->p_comment,true);
		$criteria->compare('info_detail',$this->info_detail,true);
		$criteria->compare('p_specs',$this->p_specs,true);
		$criteria->compare('unit_price',$this->unit_price);
		$criteria->compare('images',$this->images,true);
		$criteria->compare('create_datetime',$this->create_datetime,true);
		$criteria->compare('update_datetime',$this->update_datetime,true);
		$criteria->compare('show',$this->show);
		$criteria->compare('del_flg',$this->del_flg);
		$criteria->addCondition("t.del_flg != '1' AND t.show !='1'");

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	public function getProductId()
	{
		$stringName = $_POST ['Products'] ['p_type_id'];
		$sql = ProductsType::model ()->findAll ( array (
				'condition' => 'id=' . $stringName
		) );
		foreach ( $sql as $value ) {
			// print_r($value->type_name);die;
			$strName = $value->type_name;
			$strId = "";
			for($i = 1; $i < strlen ( $strName ); $i ++) {
				if ($strName [$i - 1] == ' ' && $strName [$i] != ' ') {
					$strId = $strName [0] . $strName [$i];
				}
			}
			if ($strId == "") {
				$strId = $strName [0] . $strName [1];
			}
		}
		return mb_strtoupper ( $strId );
	}
	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Products the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}
